<?php

App::import('Sanitize');

class UsersController extends AppController{
	
	var $helpers = array('Html', 'Form');
	var $name = 'Users';
	var $uses = array('Message', 'User', 'Friend', 'Invite', 'RequestFriend', 'Post');
	
	function register(){
		//if the form is submitted
		if(!empty($this->data)){
			//Some sanitize
			$this->data['User']['email_addr'] = Sanitize::paranoid($this->data['User']['email_addr'], array('@', '.', '-', '+','_'));
			$this->data['User']['first_name'] = Sanitize::paranoid($this->data['User']['first_name']);
			$this->data['User']['last_name'] = Sanitize::paranoid($this->data['User']['last_name']);

			if (($this->data['User']['passwd'] == $this->data['User']['repeat_passwd']) && $this->data['User']['passwd']) {
				$this->data['User']['passwd'] = md5($this->data['User']['passwd']);
				if($this->User->save($this->data)){
					$user = $this->User->find('first', array(
                                              'conditions' => array('User.email_addr' => $this->data['User']['email_addr'])));

					//Moving and renaming the image uploaded
					if($this->data['User']['image']['tmp_name']){

						$target_path = 'img/profile/user/'.$user['User']['id'].'.jpg';

						move_uploaded_file($this->data['User']['image']['tmp_name'], $target_path);
					}

					$this->Session->setFlash('You have registered successfully.', 'default', array('class' => 'success'));
					$this->redirect(array('action' => 'login'));

				} else {
					$this->data['User']['passwd'] = '';
					$this->data['User']['repeat_passwd'] = '';
				}
			} else {
				$this->Session->setFlash('Password must match.');
				$this->data['User']['passwd'] = '';
				$this->data['User']['repeat_passwd'] = '';
			}
		}
	}

	function login(){
		if($this->data){
			$email = $this->data['User']['email_addr'];
			$pass = $this->data['User']['passwd'];

			//Some sanitize
			$pass = Sanitize::paranoid($pass,array('_'));
			$email = Sanitize::paranoid($email,array('_'),array('@', '.', '-', '+','_'));

			$user = $this->User->find('first', array('conditions'=>array('User.email_addr'=>$this->data['User']['email_addr'])));

			if($user && ($user['User']['passwd'] == md5($this->data['User']['passwd']))){
				$this->Session->write('account_type', 'user');
				$this->Session->write('user',$user);
				$this->redirect(array('controller' => 'events', 'action'=>'index'));
			} else {
				$this->Session->setFlash('Invalid login.');
			}
		}
	}

	function logout(){
		$this->Session->destroy();
		$this->redirect(array('action' => 'login'));
	}

	function edit_profile() {
		//if the form is submitted
		if(!empty($this->data)){
			$user = $this->Session->read('user');
			$this->User->id = $user['User']['id'];
			if($this->User->save($this->data)){
				$new_user = $this->User->find('first', array(
                                              'conditions' => array('User.id' => $user['User']['id'])));

				//Moving and renaming the image uploaded
				if($this->data['User']['image']['tmp_name']){

					$target_path = 'img/profile/user/' . $new_user['User']['id'] . '.jpg';

					move_uploaded_file($this->data['User']['image']['tmp_name'], $target_path);
				}

				$this->Session->write('user',$new_user);

				$this->Session->setFlash('Your profile information has been successfully updated.', 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'edit_profile'));
			}
		}

		$this->data = $this->Session->read('user');
	}
	
	function profile($id = null) {
		if ($this->Session->read('account_type') != 'user') {
            $this->Session->setFlash('Access denied.');
            $this->redirect(array('action' => 'index'));
        }
        
        $blogs = $this->User->Blog->find('list', 
			array('fields' => array('Blog.id', 'Blog.subject'), 
	  		'conditions' => array('user_id' => $id),
	  		'order' => array('modified' => 'DESC')));
	  	$this->set(compact('blogs'));
		
		
        $this->User->id = $id;
        $user = $this->User->read();
      	$this->set('user', $user);
	   
      	$posts = $this->Post->find('all', array('conditions'=>array('Post.user_id'=>$id)));
      	$this->set('posts', $posts);
      	$this->log($posts, 'debug');
      	
      	$session_user = $this->Session->read('user');
      	$this->set('session_user', $session_user);
      	
      	$are_friends = false;
		if ($session_user['User']['id'] < $user['User']['id']) {
			$are_friends=$this->Friend->query("select count(*) as result from friends where user1_id = " . $session_user['User']['id'] . " and user2_id = " . $user['User']['id']);	
 		} else {
 			$are_friends=$this->Friend->query("select count(*) as result from friends where user1_id = " . $user['User']['id'] . " and user2_id = " . $session_user['User']['id']);	
 		}
 		$this->set('are_friends', $are_friends[0][0]);
	}
	
	
	

	function show_users() {
		$curr_session_user = $this->Session->read('user');
		$this->set('curr_user', $curr_session_user);
		$this->set('users', $this->User->find('all'));
		$friends = $this->Friend->query("SELECT * FROM friends as Friend 
										WHERE user1_id = " . $curr_session_user['User']['id'] . 
										" OR user2_id = " . $curr_session_user['User']['id'], 
										$cachequeries = false);
		$this->set('friends', $friends);
		$request_friends = $this->RequestFriend->query("SELECT * FROM request_friends as RequestFriend
														WHERE requestor_id = " . $curr_session_user['User']['id'],
														$cachequeries = false);
		$this->set('request_friends', $request_friends);
	}
	
	
		function invite_choice($event_id = null) {
		$this->autoRender = false;
		$user = $this->Session->read('user');
	
		if (!empty($this->data)) {
			$tableInput = array();
			$tableInput['Invite']['user_id'] = $user['User']['id'];
			$tableInput['Invite']['event_id'] = $event_id;
			$tableInput['Invite']['status'] = $this->data['User']['status'];

			$this->User->Invite->save($tableInput);
			$this->Session->setFlash('Choice saved.');
			$this->redirect(array('controller' => 'events', 'action' => 'index'));
		}
	}
	
}

?>
